package cn.eslm.flash.api.controller;

import cn.eslm.flash.api.utils.ApiConstants;
import cn.eslm.flash.bean.core.ShiroUser;
import cn.eslm.flash.bean.entity.system.User;
import cn.eslm.flash.bean.vo.front.Rets;

import cn.eslm.flash.bean.vo.query.SearchFilter;
import cn.eslm.flash.security.JwtUtil;
import cn.eslm.flash.security.ShiroFactroy;
import cn.eslm.flash.service.system.AccountService;
import cn.eslm.flash.service.system.UserService;
import cn.eslm.flash.utils.HttpUtil;
import cn.eslm.flash.utils.MD5;
import cn.eslm.flash.utils.Maps;
import cn.eslm.flash.utils.StringUtil;
import org.nutz.mapl.Mapl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URLEncoder;


@RestController
@RequestMapping("/account")
public class AccountController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private AccountService accountService;
    private static final String APP_ID = "AKIDbz6vUpbXmmX1FAq1PXxc1A4lDBxULBLD";
    private static final String APP_SECRET = "sVu1uXw6KJDwEG2e2AAdroUt4XrvoSqK";
    private static final String VERIFY_URI = "https://ssl.captcha.qq.com/ticket/verify?aid=%s&AppSecretKey=%s&Ticket=%s&Randstr=%s&UserIP=%s";

    public static int verifyTicket(String ticket, String rand, String userIp) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet;
        CloseableHttpResponse response = null;
        try {
            httpGet = new HttpGet(String.format(VERIFY_URI,
                    APP_ID,
                    APP_SECRET,
                    URLEncoder.encode(ticket, "UTF-8"),
                    URLEncoder.encode(rand, "UTF-8"),
                    URLEncoder.encode(userIp, "UTF-8")
            ));
            response = httpclient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String res = EntityUtils.toString(entity);
                System.out.println(res); // 临时输出

                JSONObject result = JSON.parseObject(res);
                // 返回码
                int code = result.getInteger("response");
                // 恶意等级
                int evilLevel = result.getInteger("evil_level");

                // 验证成功
                if (code == 1) return evilLevel;
            }
        } catch (java.io.IOException e) {
            // 忽略
        } finally {
            try {
                response.close();
            } catch (Exception ignore) {
            }
        }

        return -1;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(@RequestParam("username") String userName,
                        @RequestParam("password") String password) {
        try {
            logger.info("用户登录:" + userName + ",密码:" + password);
            if (verifyTicket(APP_ID, APP_SECRET, VERIFY_URI) != -1)
                return Rets.failure("登录时失败");
            User user = userService.findByAccount(userName);
            System.out.println("名字：" + user.getAccount());
            if (user == null) {
                return Rets.failure("该用户不存在");
            }
            String passwdMd5 = MD5.md5(password, user.getSalt());
            if (!(user.getPassword().equals(passwdMd5))) {
                return Rets.failure("输入的密码错误");
            }
            String token = JwtUtil.sign(user);
            Map<String, String> result = new HashMap<>(1);
            logger.info("token:{}", token);
            result.put("token", token);
            result.put("account", userName);
            return Rets.success(result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return Rets.failure("登录时失败");
    }


    @RequestMapping(value = "/wechat/login", method = RequestMethod.POST)
    public Object wechat_login(
            @RequestParam("userInfo") String userInfo,
            @RequestParam("signature") String signature,
            @RequestParam("sex") int sex,
            @RequestParam("address") String address) {
        User user = userService.findByAccount(userInfo);
        System.out.println("地址："+address);
        System.out.println("地址："+sex);
        if (user == null) {
            User user1 = new User();
            user1.setAvatar(signature);
            user1.setName(userInfo);
            user1.setStatus(1);
            user1.setSex(sex);
            user1.setEmail("待完善");
            Long a = Long.valueOf(5);
            user1.setDeptid(a);
            user1.setRoleid("3");
            user1.setAccount(userInfo);
            user1.setPhone("待完善");
            Long b = Long.valueOf(4);
            user1.setId(b);
            user1.setPassword(MD5.md5("123456", "password"));
            Date date = new Date();
            date.getTime();
            user1.setCreateTime(date);
            userService.insert(user1);
            String token = JwtUtil.sign(user1);
            Map<String, String> result = new HashMap<>(1);
            logger.info("token:{}", token);
            result.put("token", token);
            result.put("account", userInfo);
            System.out.println("创建成功");
            return Rets.success(result);
        } else if (user.getStatus() == 1) {
            user.setAvatar(signature);
            userService.update(user);
            String token = JwtUtil.sign(user);
            Map<String, String> result = new HashMap<>(1);
            logger.info("token:{}", token);
            result.put("token", token);
            result.put("account", userInfo);
            System.out.println("登录成功");
            return Rets.success(result);
        } else {
            return Rets.failure("账号被冻结");
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Object logout() {
        HttpServletRequest request = HttpUtil.getRequest();
        String token = this.getToken(HttpUtil.getRequest());
        accountService.logout(token);
        Long idUser = getIdUser(request);

        return Rets.success();
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public Object info() {
        HttpServletRequest request = HttpUtil.getRequest();
        Long idUser = null;
        try {
            idUser = getIdUser(request);
        } catch (Exception e) {
            return Rets.expire();
        }
        if (idUser != null) {
            User user = userService.get(idUser);
            if (StringUtil.isEmpty(user.getRoleid())) {
                return Rets.failure("该用户未配置权限");
            }
            ShiroUser shiroUser = ShiroFactroy.me().shiroUser(user);
            Map map = Maps.newHashMap("name", user.getName(), "role", "admin", "roles", shiroUser.getRoleCodes());
            map.put("permissions", shiroUser.getUrls());
            Map profile = (Map) Mapl.toMaplist(user);
            profile.put("dept", shiroUser.getDeptName());
            profile.put("roles", shiroUser.getRoleNames());
            map.put("profile", profile);

            return Rets.success(map);
        }
        return Rets.failure("获取用户信息失败");
    }

    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    public Object updatePwd(String oldPassword, String password, String rePassword) {
        try {
            User user = userService.get(getIdUser(HttpUtil.getRequest()));
            logger.info("oldPassword:{},password:{},rePassword:{}", oldPassword, password, rePassword);
            if (!MD5.md5(oldPassword, user.getSalt()).equals(user.getPassword())) {
                return Rets.failure("旧密码输入错误");
            }
            if (!password.equals(rePassword)) {
                return Rets.failure("新密码前后不一致");
            }
            user.setPassword(MD5.md5(password, user.getSalt()));
            userService.update(user);
            User user2 = userService.get(getIdUser(HttpUtil.getRequest()));
            logger.info("新密码" + MD5.md5(password, user2.getSalt()));
            return Rets.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return Rets.failure("更改密码失败");
    }

    //
    @RequestMapping(value = "/userinfo", method = RequestMethod.POST)
    public Object userinfo(String account) {
        User byAccount = userService.findByAccount(account);
        return Rets.success(byAccount);
    }


}
